package com.molihub.controller;

import com.alibaba.fastjson.JSONObject;
import com.molihub.entity.Article;
import com.molihub.entity.ResponseResult;
import com.molihub.utils.FileUploadUtils;
import com.molihub.utils.LogUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: PostController
 * @Description: 对应与短文本内容发布的控制器
 * @author: GGBOY
 * @date 2020/2/11 14:57
 * @Version: 1.0
 **/
@Controller
public class PostController extends BaseController {
    private Logger logger = LogUtils.getInstance(PostController.class);

    /**
     * 主页上发布状态
     *
     * @param article 发布的内容
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/7
     */
    @PostMapping("/publishShortContent")
    public String publishShortContent(Article article, @RequestParam("files") MultipartFile[] files) {
        ResponseResult responseResult;
        article.setUserId(loginUser.getUserId());
        logger.info("publishShortContent--------> " + article.toString());
        List<JSONObject> objectList = new ArrayList<>();
        for (MultipartFile file : files) {
            JSONObject json = new JSONObject();
            logger.info("文件名————————————————————>" + file.getOriginalFilename());
            if(file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
                responseResult = FileUploadUtils.uploadImageWithPost(file);
                json.put("path", responseResult != null ? responseResult.getUrl() : null);
                objectList.add(json);
            }
        }
        logger.info("文件大小：" + objectList.size());
        if(objectList.size() > 0){
            article.setImgPath(JSONObject.toJSONString(objectList));
        }
        article.setType(2);
        article.setPublishTime(new Date());
        articleService.publishArticle(article);
        logger.info("发表状态成功！信息：" + article);
        return "redirect:";
    }
}
